package com.example.examsystem.controller;

import com.example.examsystem.dto.ExamAnswerDto;
import com.example.examsystem.dto.ExamRecordDto;
import com.example.examsystem.dto.ExamStatisticsDto;
import com.example.examsystem.dto.PageResponse;
import com.example.examsystem.service.ExamRecordService;
import com.example.examsystem.utils.SecurityUtils;
import com.example.examsystem.utils.IpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 考试记录控制器
 * 处理考试记录的CRUD操作
 */
@RestController
@RequestMapping("/exam-records")
@RequiredArgsConstructor
@Slf4j
public class ExamRecordController {
    
    private final ExamRecordService examRecordService;
    
    /**
     * 获取考试记录列表
     * @param page 页码
     * @param size 每页大小
     * @param examId 考试ID
     * @param userId 用户ID
     * @param username 用户名
     * @param examTitle 考试标题
     * @param status 状态
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 分页考试记录列表
     */
    @GetMapping
    @PreAuthorize("hasAuthority('grade:list:view')")
    public ResponseEntity<PageResponse<ExamRecordDto>> getExamRecords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long examId,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String examTitle,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        log.info("查询考试记录列表 - 页码: {}, 大小: {}, 考试ID: {}, 用户ID: {}, 用户名: {}, 考试标题: {}, 状态: {}", 
                page, size, examId, userId, username, examTitle, status);
        PageResponse<ExamRecordDto> records = examRecordService.getExamRecords(
            page, size, examId, userId, username, examTitle, status, startTime, endTime);
        return ResponseEntity.ok(records);
    }
    
    /**
     * 获取考试记录详情
     * @param id 记录ID
     * @return 考试记录详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('grade:list:view')")
    public ResponseEntity<ExamRecordDto> getExamRecord(@PathVariable Long id) {
        log.info("获取考试记录详情 - ID: {}", id);
        ExamRecordDto record = examRecordService.getExamRecord(id);
        return ResponseEntity.ok(record);
    }
    
    /**
     * 开始考试
     * @param examId 考试ID
     * @param request HTTP请求
     * @return 考试记录
     */
    @PostMapping("/start/{examId}")
    @PreAuthorize("hasAuthority('exam:take')")
    public ResponseEntity<ExamRecordDto> startExam(@PathVariable Long examId, HttpServletRequest request) {
        log.info("开始考试 - 考试ID: {}", examId);
        
        Long userId = SecurityUtils.getCurrentUserId();
        String ipAddress = IpUtils.getIpAddress(request);
        String userAgent = request.getHeader("User-Agent");
        
        ExamRecordDto record = examRecordService.startExam(examId, userId, ipAddress, userAgent);
        return ResponseEntity.ok(record);
    }
    
    /**
     * 提交答案
     * @param recordId 记录ID
     * @param request 提交请求
     * @return 更新的考试记录
     */
    @PostMapping("/{recordId}/submit")
    @PreAuthorize("hasAuthority('exam:take')")
    public ResponseEntity<ExamRecordDto> submitAnswers(@PathVariable Long recordId, 
                                                      @Valid @RequestBody Map<String, Object> request) {
        log.info("提交答案 - 记录ID: {}", recordId);
        
        @SuppressWarnings("unchecked")
        List<ExamAnswerDto> answers = (List<ExamAnswerDto>) request.get("answers");
        
        ExamRecordDto record = examRecordService.submitAnswers(recordId, answers);
        return ResponseEntity.ok(record);
    }
    
    /**
     * 完成考试
     * @param recordId 记录ID
     * @return 完成的考试记录
     */
    @PostMapping("/{recordId}/finish")
    @PreAuthorize("hasAuthority('exam:take')")
    public ResponseEntity<ExamRecordDto> finishExam(@PathVariable Long recordId) {
        log.info("完成考试 - 记录ID: {}", recordId);
        ExamRecordDto record = examRecordService.finishExam(recordId);
        return ResponseEntity.ok(record);
    }
    
    /**
     * 获取用户的考试记录
     * @param page 页码
     * @param size 每页大小
     * @param examId 考试ID
     * @param status 状态
     * @return 分页考试记录列表
     */
    @GetMapping("/my")
    @PreAuthorize("hasAuthority('exam:take')")
    public ResponseEntity<PageResponse<ExamRecordDto>> getMyExamRecords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long examId,
            @RequestParam(required = false) String status) {
        log.info("获取用户考试记录 - 页码: {}, 大小: {}, 考试ID: {}, 状态: {}", page, size, examId, status);
        
        Long userId = SecurityUtils.getCurrentUserId();
        PageResponse<ExamRecordDto> records = examRecordService.getMyExamRecords(userId, page, size, examId, status);
        return ResponseEntity.ok(records);
    }
    
    /**
     * 获取考试统计信息
     * @param examId 考试ID
     * @return 统计信息
     */
    @GetMapping("/statistics/{examId}")
    @PreAuthorize("hasAuthority('grade:list:view')")
    public ResponseEntity<ExamStatisticsDto> getExamStatistics(@PathVariable Long examId) {
        log.info("获取考试统计信息 - 考试ID: {}", examId);
        ExamStatisticsDto statistics = examRecordService.getExamStatistics(examId);
        return ResponseEntity.ok(statistics);
    }
}